package com.agile.leetcode.url.longtoshort;

import cn.hutool.cache.CacheUtil;
import cn.hutool.cache.impl.LRUCache;
import cn.hutool.core.codec.Base62;
import cn.hutool.core.util.HashUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import org.apache.commons.lang3.StringUtils;

/**
 * @author chenzhangkun
 * @ClassName LongUrlToShortUrl
 * @description: TODO
 * @date 2024年08月20日
 */
public class LongUrlToShortUrl {
	LRUCache<Object, Object> lruCache = CacheUtil.newLRUCache(100);

	public String generateShortUrl(String longUrl){
		if (StrUtil.isBlank(longUrl)){
			throw new RuntimeException("长连接错误");

		}
		String shortUrl =(String) lruCache.get(longUrl);
		if (StrUtil.isNotBlank(shortUrl)){
			return shortUrl;
		}
		return getShortUrl(longUrl, getLongUrlRandom(longUrl));
	}

	private String getShortUrl(String rawUrl,String longUrl) {
		// 该长链接的hash
		long hash = HashUtil.murmur64(longUrl.getBytes());
		String base62 = Base62.encode(String.valueOf(hash));
		if (StrUtil.isEmpty(base62)){
			throw new RuntimeException("长连接错误");
		}
		String shortUrl = StringUtils.substring(base62, 6);
		ShortUrl shortUrl1=new ShortUrl(rawUrl,longUrl);
		try {
			ShortUrlDao shortUrlDao=new ShortUrlDao();
			int result=shortUrlDao.insert(shortUrl1);
			if (result==1){
				// 插入成功，该短链接不存在
				// 更新缓存
				lruCache.put(longUrl,shortUrl);
			}

		}catch (Exception e){
			// 有冲突，捕获异常，继续修改插入
			lruCache.put(longUrl,shortUrl);
			return getShortUrl(longUrl, getLongUrlRandom(shortUrl));


		}


		return null;
	}

	private String getLongUrlRandom(String longUrl) {
		return longUrl + RandomUtil.randomString(6);  // 解决冲突多的问题，随机字符串
	}

	public static class ShortUrl{
		private String longUrl;
		private String shortUrl;

		public ShortUrl(String longUrl, String shortUrl) {
			this.longUrl = longUrl;
			this.shortUrl = shortUrl;
		}

		public String getLongUrl() {
			return longUrl;
		}

		public void setLongUrl(String longUrl) {
			this.longUrl = longUrl;
		}

		public String getShortUrl() {
			return shortUrl;
		}

		public void setShortUrl(String shortUrl) {
			this.shortUrl = shortUrl;
		}
	}

	public static class ShortUrlDao{
		public int insert(ShortUrl shortUrl){
			// 唯一索引shortUrl有冲突抛出异常，没有返回1
			return 1;

		}

	}


}
